import React, { useState } from 'react';
import styles from './index.less';
import { Spin, Collapse, Radio, Tooltip, Table, Typography, Upload, message, Popconfirm, Modal } from 'antd';
import { PlusOutlined, DeleteFilled, CaretRightOutlined } from '@ant-design/icons'
import IconFont from '@/components/IconFont';
import DrawInitForm from '@/components/DrawInitForm';
import { useModel } from 'umi'
import { useRequest, useAsyncEffect } from 'ahooks'
import { getFetch, postFetch } from '@/utils/doFetch';
import { useMemo } from 'react';
import moment from 'moment';
import AutoTable from '@/components/AutoTable/mtable';

const { Panel } = Collapse;
const { Paragraph } = Typography;
const { Dragger } = Upload;


function Mydata() {
    const [editing, setediting] = useState(false);
    const [activeKey, setactiveKey] = useState(["1"]);
    const { initialState, setInitialState } = useModel("@@initialState");
    const [drawconfig, setdrawconfig] = useState({
        title: "",
        visible: false,
        placement: "left",
        fields: {

        }
    });
    const [modalconfig, setmodalconfig] = useState({
        title: "",
        width: 1200,
        visible: false,
    });
    const [destroy, setdestroy] = useState(false);
    const { data, error, loading, refresh } = useRequest(() => getFetch({ url: "/api/data_group", params: { is_all: 1 } }));
    const action = useRequest(postFetch, {
        manual: true,
        formatResult: (res) => res,
        debounceWait: 200,
        onSuccess: (result, params) => {
            
            if (result.code == 0) {
                message.success("操作成功");
                setdrawconfig(s => ({ ...s, visible: false }));
                refresh()
            } else {
            }
        }
    })

    let list = useMemo(() => {
        return data?.data?.dataList ?? []
    }, [data])


    let adddom = (placement) => (<div className='diybtn' onClick={() => {
        setdestroy(false);
        setTimeout(() => {
            setdrawconfig(s => {
                return {
                    ...s,
                    val: "addon",
                    visible: true,
                    title: "新建数据组",
                    placement: placement ?? "left",
                    fields: {
                        "name": {
                            "value": null,
                            "type": "input",
                            "title": "数据组名称",
                            "name": [
                                "name"
                            ],
                            "required": true
                        },
                    }
                }
            })
        }, 200);

    }}>
        <PlusOutlined style={{ marginRight: 6 }}></PlusOutlined>
        <span>新建数据组</span>
    </div>)



    const uploadprops = (item) => {
        return {
            name: 'file',
            multiple: true,
            data: { data_group_id: item.id },
            action: '/gauss/api/data_file',
            headers: {
                'Authorization': localStorage.getItem("TOKEN")
            },
            onChange(info) {
                const { status } = info.file;
                if (status !== 'uploading') {
                }
                if (status === 'done') {
                    if (info.file.response.code == 0) {
                        message.success(`${info.file.name} 文件上传成功`);
                        refresh()
                    } else {
                        message.warn(info.file.response.message)
                    }
                } else if (status === 'error') {
                    message.error(`${info.file.name} 文件上传失败`);
                }
            },
            onDrop(e) {
                console.log('Dropped files', e.dataTransfer.files);
            },
            showUploadList: false
        };
    }


    return (<div>
        {
            !destroy && <DrawInitForm
                {...drawconfig}
                onClose={() => {
                    setdrawconfig((s) => ({ ...s, visible: false }))
                }}
                col={{ span: 24 }}
                submitData={(values) => {
                    if (drawconfig.val == "addon") {
                        action.run({ url: "/api/data_group", params: { ...values } })
                    }
                }}
                afterVisibleChange={(visible) => {
                    if (!visible) {
                        setdestroy(true);
                    }
                }}
            ></DrawInitForm>
        }


        <Modal
            {...modalconfig}
            onCancel={() => {
                setmodalconfig((s) => ({ ...s, visible: false }))
            }}
            destroyOnClose={true}
            footer={false}
        >
            <AutoTable
                columns={modalconfig.columns ?? []}
                path={modalconfig.path}
                extraparams={modalconfig.extraparams}
                dataSource={modalconfig.dataSource}
            />
        </Modal>

        <Spin size="large" spinning={loading}>
            <div className="fixedheader databg" style={{ transition: "all 0.4s", top: initialState.showaction ? 48 : 0 }}>
                <div className="container" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", height: "100%" }}>
                    <div style={{ color: "#fff", fontWeight: "bolder" }}>
                        说明:同一数据组底下的所有数据文件必须具有相同的数据结构，以便于多次使用同样的报告模板，提高报告生成的效率，状态为异常的数据文件将无法生成报告。
                    </div>
                    {
                        adddom("right")
                    }
                </div>

            </div>

            <div className='imgbg' style={{ backgroundImage: `url(${require("@/assets/mydatabg.jpg")})`, height: 300 }}>
                <div className="container" style={{ display: "flex", height: "100%" }}>
                    <div className={styles.left}>
                        <h2>数据组说明</h2>
                        <p>
                            同一数据组底下的所有数据文件必须具有相同的数据结构，以便于多次使用同样的报告模板，<br />
                            提高报告生成的效率，状态为异常的数据文件将无法生成报告。
                        </p>
                        {adddom()}
                    </div>
                    <div className={styles.right}>
                        <img src={require("@/assets/ed.png")} alt="" />
                        <img src={require("@/assets/ed_1.png")} alt="" />
                    </div>
                </div>
            </div>

            <div className="container" style={{ padding: "12px 0" }}>
                <Collapse
                    expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
                    activeKey={activeKey}
                    onChange={(val) => {
                        if (editing) return;
                        setactiveKey(val);
                    }}
                    ghost
                >
                    {
                        list.map((it, i) => {
                            return <Panel
                                key={(i + 1).toString()}
                                header={<div style={{ display: "flex", alignItems: "center" }} onClick={(e) => {
                                    e.stopPropagation()
                                }}>
                                    <Paragraph
                                        editable={{
                                            onStart: () => {
                                                setediting(true)
                                            },
                                            onChange: (val) => {
                                                console.log(val);
                                                action.run({ url: "/api/data_group/" + it.id, params: { name: val}, method: "PUT" })
                                            },
                                            onEnd: (val) => {
                                                console.log(val)
                                                setediting(true)
                                                setTimeout(() => {
                                                    setediting(false)
                                                }, 20)

                                            }
                                        }}
                                    >
                                        {it?.name}
                                    </Paragraph>
                                </div>}
                                extra={<div onClick={(e) => {
                                    e.stopPropagation();
                                }}>
                                    <Tooltip title="删除数据组">
                                        <Popconfirm placement="bottom" title={"是否删除？"} onConfirm={() => {
                                            action.run({ url: "/api/data_group/" + it.id, params: {}, method: "DELETE" })
                                        }} okText="删除" cancelText="取消">
                                            <IconFont type='icon-delete' style={{ color: "red", fontSize: 18 }} />
                                        </Popconfirm>
                                    </Tooltip>
                                </div>}>
                                <Dragger {...uploadprops(it)}>
                                    <div style={{ position: "relative", paddingBottom: it?.files?.length > 0 ? 0 : 42 }}>
                                        <div onClick={(e) => {
                                            e.stopPropagation();
                                        }}>
                                            <Table
                                                columns={[
                                                    {
                                                        title: '数据文件',
                                                        dataIndex: 'file_name',
                                                        render: (text, record) => <a href={record.file_path} target="_blank">{text}</a>,
                                                    },
                                                    {
                                                        title: '变量数量',
                                                        dataIndex: 'variable_num',
                                                    },
                                                    {
                                                        title: '状态',
                                                        dataIndex: 'status',
                                                        render: (text) => text == "success" ? "成功" : "失败",

                                                    },
                                                    {
                                                        title: '创建时间',
                                                        dataIndex: 'created_at',
                                                        sorter: (a, b) => moment(a.created_at).valueOf() - moment(b.created_at).valueOf(),
                                                        render: (text, record) => <span>
                                                            {text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : '-'}
                                                        </span>
                                                    },
                                                    {
                                                        title: '操作',
                                                        dataIndex: 'option',
                                                        width: 200,
                                                        render: (text, record) => {
                                                            return [
                                                                <a onClick={() => {
                                                                    setmodalconfig(s => {
                                                                        return {
                                                                            ...s,
                                                                            visible: true,
                                                                            title: "变量视图:" + record.file_name,
                                                                            columns: [
                                                                                {
                                                                                    title: '编号',
                                                                                    dataIndex: 'index',
                                                                                    render: (text, record, index) => `${index + 1}`,
                                                                                    search: false
                                                                                },
                                                                                {
                                                                                    title: '变量名称',
                                                                                    dataIndex: 'variable_name',
                                                                                },
                                                                                {
                                                                                    title: '变量类型',
                                                                                    dataIndex: 'variable_type',
                                                                                    search: false
                                                                                },
                                                                                // {
                                                                                //     title: '变量来源',
                                                                                //     dataIndex: 'source',
                                                                                //     search:false
                                                                                // },
                                                                                {
                                                                                    title: '变量来源名称',
                                                                                    dataIndex: 'source_name',
                                                                                    search: false
                                                                                }
                                                                            ],
                                                                            path: "/api/data_file/variable_view",
                                                                            extraparams: { id: record.id }
                                                                        }
                                                                    })
                                                                }}>
                                                                    变量视图
                                                                </a>,
                                                                <a style={{ padding: "0 12px" }} onClick={async () => {
                                                                    let res = await getFetch({ url: "/api/data_file/data_view", params: { id: record.id } });
                                                                    console.log(res?.data?.variables);
                                                                    setmodalconfig(s => {
                                                                        return {
                                                                            ...s,
                                                                            visible: true,
                                                                            title: "数据视图:" + record.file_name,
                                                                            columns: res?.data?.variables,
                                                                            dataSource: res?.data?.data,
                                                                        }
                                                                    })
                                                                }}>
                                                                    数据视图
                                                                </a>,
                                                                <Popconfirm placement="bottom" title={"是否删除？"} onConfirm={() => {
                                                                    action.run({ url: "/api/data_file/" + record.id, params: {}, method: "DELETE" })
                                                                }} okText="删除" cancelText="取消">
                                                                    <a>
                                                                        删除
                                                                    </a>
                                                                </Popconfirm>
                                                            ]
                                                        }
                                                    }
                                                ]}
                                                dataSource={it?.files ?? []}
                                            />
                                        </div>
                                        <p style={{ textAlign: "left", marginTop: -6, marginBottom: 6, position: "absolute", left: 0, bottom: it?.files?.length > 0 ? 18 : 0, zIndex: 6 }}>
                                            <a>点击此处</a> 或 拖拽文件置表格区域上传新数据文件
                                            <span style={{ color: "#999", paddingLeft: 12 }}>
                                                支持扩展名：XLS，文件小于5M，同一数据组下的数据文件必须具有相同的变量
                                            </span>
                                        </p>
                                    </div>


                                </Dragger>
                            </Panel>

                        })
                    }



                </Collapse>

            </div>
        </Spin>
    </div>);
}

export default Mydata;